package nix.thread;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class Test1 {

	/**
	 * ThreadLocal用法
	 */
	@Test
	public void fun1() {

		ThreadLocal<String> tl = new ThreadLocal<String>();
		// 存
		tl.set("hello");
		// 取
		System.out.println(tl.get());
		// 删
		tl.remove();
	}

	/**
	 * 线程内共享，线程间隔离
	 */
	@Test
	public void fun2() {
		final ThreadLocal<String> tl = new ThreadLocal<String>();
		tl.set("hello");
		System.out.println(Thread.currentThread().getName());
		System.out.println(tl.get());

		new Thread() {
			public void run() {
				System.out.println(Thread.currentThread().getName());
				System.out.println(tl.get());
			}
		}.start();
	}

	/**
	 * 使用当前线程为key的Map实现ThreadLocal
	 */
	@Test
	public void fun3() {
		final Map<Thread, String> map = new HashMap<Thread, String>();
		map.put(Thread.currentThread(), "hello");
		System.out.println(Thread.currentThread().getName());
		System.out.println(map.get(Thread.currentThread()));

		new Thread() {
			public void run() {
				System.out.println(Thread.currentThread().getName());
				System.out.println(map.get(Thread.currentThread()));
			}
		}.start();
	}
}

/**
 * 简单实现ThreadLocal
 * 
 * @author berry
 * 
 * @param <T>
 */
class TL<T> {
	private Map<Thread, T> map = new HashMap<Thread, T>();

	public void set(T t) {
		map.put(Thread.currentThread(), t);
	}

	public T get() {
		return map.get(Thread.currentThread());
	}

	public void remove() {
		map.remove(Thread.currentThread());
	}
}